package com.twohand.admin.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.twohand.admin.Service.MenuService;
import com.twohand.admin.Util.JwtUtil;
import com.twohand.utils.Response.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    MenuService menuService;
    public final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("============token拦截处=============");
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        log.info("Client IP address: " + ipAddress.split(",")[0]);
        log.info("token:{};",token);
        //拦截token
        if(StringUtils.isEmpty(token)){
            throw new BaseException(401,"token不能为空");
        }
        try{
            DecodedJWT decodedJWT =  JwtUtil.decodeToken(token);
//            CurrentUser.id = decodedJWT.getClaim("id").asInt();
//            CurrentUser.nickname = decodedJWT.getClaim("username").asString();
//            CurrentUser.openid = decodedJWT.getClaim("openid").asString();
//            CurrentUser.permissions = menuService.getPermissionByUserId(CurrentUser.id);
//            System.out.println(CurrentUser.id);
//            System.out.println(CurrentUser.nickname);
//            System.out.println(CurrentUser.openid);


//            Map<String, Claim> list = decodedJWT.getClaims();
//           List<String> list = decodedJWT.getAudience();
//           System.out.println(list.size());
//            for(Map.Entry<String , Claim> l : list.entrySet()){
//                String k = l.getKey();
//                String s = l.getValue().asString();
//                System.out.println("解出来的字符串："+k+"--"+s);
//            }
        }catch (SignatureVerificationException e){
            throw new BaseException(401,"非法签名");
        }
        catch (TokenExpiredException e){
            throw new BaseException(401,"token过期");
        }
        catch (AlgorithmMismatchException e){
            throw new BaseException(401,"token算法不一致");
        }
        catch (Exception e){
            e.printStackTrace();
            throw new BaseException(401,"token 无效");
        }
        return true;
    }
}
